/**
 * 文件管理工具
 */
import Page from './Page'
export default class FileManager {
    constructor(ele) {
        this.pages = new Set()
        this.current = null
        this.ele = ele
    }
    static build(descr) {
        let page_arr = [];
        descr.pages.forEach(val=>{
            page_arr.push(Page.build(val))
        })
        let manager = new FileManager(document.getElementById('filelist'))
        manager.pages = new Set(page_arr)
        manager.current = (page_arr.length > 0?page_arr[0]:null)
        return manager
    }
    toJson() {
        let page_arr = [];
        [...this.pages].forEach(val=>{
            page_arr.push(val.toJson())
        })

        return {
            pages: page_arr,
            current: this.current === null?{}:this.current.toJson()
        }
    }
    add(page) {
        this.pages.add(page)
        this.toView()
    }
    remove(filename,_callback) {
        for(let page of this.pages) {
            if(page.name == filename) {
                this.pages.delete(page)
                if(this.pages.size > 0) {
                    this.current = this.pages.values().next()
                }
                _callback(page.file)
                break
            }
        }
    }
    switch(filename, _callback) {
        for(let page of this.pages) {
            if(page.name == filename) {
                this.current = page
                this.toView()
                _callback(page.file)
                break
            }
        }
    }
    toView() {
        let html = "<ul class='file-top'>"
        for(let page of this.pages) {
            if(this.current == page){
                html += page.file.toView(true)
            }else {
                html += page.file.toView(false)
            }
        }
        html += "</ul>"
        this.ele.innerHTML = html
    }
}
